package com.nest.WorkNest.act;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.loveplusplus.demo.fileupload.PictureUtil;
import com.nest.WorkNest.R;
import com.nest.WorkNest.adapter.PhotoAdapter;
import com.nest.WorkNest.api.Api;
import com.nest.WorkNest.config.UserInfo;
import com.nest.WorkNest.tools.PhoneHelper;
import com.nest.WorkNest.tools.Tool;
import com.orhanobut.logger.Logger;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import me.iwf.photopicker.PhotoPickerActivity;
import me.iwf.photopicker.utils.PhotoPickerIntent;

public class NewEnquiryAct extends BaseActivity implements OnClickListener {
    @Bind(R.id.tv_newenquiry_ProductLink)
    TextView tvNewenquiryProductLink;
    @Bind(R.id.tv_newenquiry_Productdetail)
    TextView tvNewenquiryProductdetail;
    private LinearLayout ll_newenquiry_name, ll_newenquiry_DemoOrNot,
            ll_newenquiry_FabricAndAccessories, ll_newenquiry_AccessoriesRemarks,
            ll_newenquiry_CommodityLabel, ll_newenquiry_Package, ll_newenquiry_Time,
            ll_newenquiry_FabricOrNot, ll_newenquiry_ProductLink, ll_newenquiry_bigTime, ll_newenquiry_Productdetail, ll_newenquiry_blank;
    private TextView tv_newenquiry_name, tv_newenquiry_DemoOrNot,
            tv_newenquiry_FabricAndAccessories, tv_newenquiry_AccessoriesRemarks,
            tv_newenquiry_CommodityLabel, tv_newenquiry_Package, tv_newenquiry_Time,
            tv_newenquiry_bigTime, tv_newenquiry_FabricOrNot;
    private Context context = NewEnquiryAct.this;
    private Intent mIntent = new Intent();
    private String name, DemoOrNot = "否", FabricAndAccessories = "包工包料", CommodityLabel = "委托采购", Package = "委托采购", Time, bigTime,
            accessoriesremarks, FabricOrNot = "是", ProductLink, productdetail;
    private Button btn_newenquiry_submit;
    private ArrayList<String> selectedPhotos = new ArrayList<>();
    private int SCREEN_WIDTH;
    private List<String> strList = new ArrayList<>();
    private int one = 0, two = 10, three = 22, four = 32, five = 1;
    @Bind(R.id.rv_newenquiry)
    RecyclerView rvNewenquiry;
    @Bind(R.id.iv_newenquiry_addpic)
    ImageView ivNewenquiryAddpic;
    private PhotoAdapter photoAdapter;
    private static int REQUEST_CODE = 10;
    private List<String> uploaded = new ArrayList<>();
    private final static int MAX_IMAGE = 3;
    private int imageCount = 0;

    public List<String> getUploaded() {
        return uploaded;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_newenquiry);
        ButterKnife.bind(this);
        SCREEN_WIDTH = PhoneHelper.getScreenWidth(context);
        initBar();
        actionbar_side_name.setVisibility(View.VISIBLE);
        actionbar_side_name.setText("新建询价单");
        ll_iv_actionbar_side_left.setVisibility(View.VISIBLE);
        back();
        System.out.println("NewEnquiryAct.onCreate====" + DemoOrNot + "===" + FabricAndAccessories + "===" + CommodityLabel + "===" + Package + "===" + one + "===" + two + "===" + three + "===" + four);
        initView();
    }

    public void previewPhoto(Intent intent) {
        startActivityForResult(intent, REQUEST_CODE);
    }

    public void initView() {
        initProgress(context, "正在提交...");
        photoAdapter = new PhotoAdapter(this, selectedPhotos);
        rvNewenquiry.setLayoutManager(new StaggeredGridLayoutManager(4, OrientationHelper.VERTICAL));
        rvNewenquiry.setAdapter(photoAdapter);
        ll_newenquiry_name = (LinearLayout) findViewById(R.id.ll_newenquiry_name);
        ll_newenquiry_DemoOrNot = (LinearLayout) findViewById(R.id.ll_newenquiry_DemoOrNot);
        ll_newenquiry_FabricAndAccessories = (LinearLayout) findViewById(
                R.id.ll_newenquiry_FabricAndAccessories);
        ll_newenquiry_AccessoriesRemarks = (LinearLayout) findViewById(
                R.id.ll_newenquiry_AccessoriesRemarks);
        ll_newenquiry_CommodityLabel = (LinearLayout) findViewById(
                R.id.ll_newenquiry_CommodityLabel);
        ll_newenquiry_Package = (LinearLayout) findViewById(R.id.ll_newenquiry_Package);
        ll_newenquiry_Time = (LinearLayout) findViewById(R.id.ll_newenquiry_Time);
        ll_newenquiry_FabricOrNot = (LinearLayout) findViewById(R.id.ll_newenquiry_FabricOrNot);
        ll_newenquiry_ProductLink = (LinearLayout) findViewById(R.id.ll_newenquiry_ProductLink);
        ll_newenquiry_Productdetail = (LinearLayout) findViewById(R.id.ll_newenquiry_Productdetail);
        ll_newenquiry_bigTime = (LinearLayout) findViewById(R.id.ll_newenquiry_bigTime);
        tv_newenquiry_name = (TextView) findViewById(R.id.tv_newenquiry_name);
        tv_newenquiry_DemoOrNot = (TextView) findViewById(R.id.tv_newenquiry_DemoOrNot);
        tv_newenquiry_FabricAndAccessories = (TextView) findViewById(
                R.id.tv_newenquiry_FabricAndAccessories);
        tv_newenquiry_AccessoriesRemarks = (TextView) findViewById(
                R.id.tv_newenquiry_AccessoriesRemarks);
        tv_newenquiry_CommodityLabel = (TextView) findViewById(R.id.tv_newenquiry_CommodityLabel);
        tv_newenquiry_Package = (TextView) findViewById(R.id.tv_newenquiry_Package);
        tv_newenquiry_Time = (TextView) findViewById(R.id.tv_newenquiry_Time);
        tv_newenquiry_FabricOrNot = (TextView) findViewById(R.id.tv_newenquiry_FabricOrNot);
        tv_newenquiry_bigTime = (TextView) findViewById(R.id.tv_newenquiry_bigTime);
        btn_newenquiry_submit = (Button) findViewById(R.id.btn_newenquiry_submit);
        ll_newenquiry_blank = (LinearLayout) findViewById(R.id.ll_newenquiry_blank);
        ll_newenquiry_name.setOnClickListener(this);
        ll_newenquiry_DemoOrNot.setOnClickListener(this);
        ll_newenquiry_FabricAndAccessories.setOnClickListener(this);
        ll_newenquiry_AccessoriesRemarks.setOnClickListener(this);
        ll_newenquiry_CommodityLabel.setOnClickListener(this);
        ll_newenquiry_Package.setOnClickListener(this);
        ll_newenquiry_Time.setOnClickListener(this);
        ll_newenquiry_FabricOrNot.setOnClickListener(this);
        ll_newenquiry_ProductLink.setOnClickListener(this);
        ll_newenquiry_bigTime.setOnClickListener(this);
        btn_newenquiry_submit.setOnClickListener(this);
        ll_newenquiry_Productdetail.setOnClickListener(this);
        ivNewenquiryAddpic.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_newenquiry_name:
                mIntent.putExtra("type", "name");
                mIntent.setClass(context, CreateAct.class);
                startActivityForResult(mIntent, 0);
                break;
            case R.id.ll_newenquiry_DemoOrNot:
                mIntent.putExtra("type", "demo");
                mIntent.setClass(context, CreateAct.class);
                startActivityForResult(mIntent, 1);
                break;
            case R.id.ll_newenquiry_FabricAndAccessories:
                mIntent.putExtra("type", "FAA");
                mIntent.setClass(context, CreateAct.class);
                startActivityForResult(mIntent, 2);
                break;
            case R.id.ll_newenquiry_AccessoriesRemarks:
                mIntent.putExtra("type", "AR");
                mIntent.setClass(context, CreateAct.class);
                startActivityForResult(mIntent, 3);
                break;
            case R.id.ll_newenquiry_CommodityLabel:
                mIntent.putExtra("type", "CL");
                mIntent.setClass(context, CreateAct.class);
                startActivityForResult(mIntent, 4);
                break;
            case R.id.ll_newenquiry_Package:
                mIntent.putExtra("type", "packages");
                mIntent.setClass(context, CreateAct.class);
                startActivityForResult(mIntent, 5);
                break;
            case R.id.ll_newenquiry_Time:
                mIntent.putExtra("type", "numbers");
                mIntent.setClass(context, CreateAct.class);
                startActivityForResult(mIntent, 6);
                break;
            case R.id.ll_newenquiry_bigTime:
                mIntent.putExtra("type", "bigtime");
                mIntent.setClass(context, CreateAct.class);
                startActivityForResult(mIntent, 11);
                break;
            case R.id.ll_newenquiry_FabricOrNot:
                mIntent.putExtra("type", "FON");
                mIntent.setClass(context, CreateAct.class);
                startActivityForResult(mIntent, 7);
                break;
            case R.id.ll_newenquiry_ProductLink:
                mIntent.putExtra("type", "PL");
                mIntent.setClass(context, CreateAct.class);
                startActivityForResult(mIntent, 8);
                break;
            case R.id.ll_newenquiry_Productdetail:
                mIntent.putExtra("type", "PD");
                mIntent.setClass(context, CreateAct.class);
                startActivityForResult(mIntent, 9);
                break;
            case R.id.iv_newenquiry_addpic:
                PhotoPickerIntent intent = new PhotoPickerIntent(NewEnquiryAct.this);
                intent.setPhotoCount(MAX_IMAGE);
                intent.setShowCamera(true);
                startActivityForResult(intent, REQUEST_CODE);
                break;
            case R.id.btn_newenquiry_submit:
                initSubmit();
                break;
        }
    }

    public void initSubmit() {
//                TextUtils.isEmpty(DemoOrNot) ||
//                TextUtils.isEmpty(FabricAndAccessories) ||
//                TextUtils.isEmpty(CommodityLabel) ||
//                TextUtils.isEmpty(Package) ||
//                TextUtils.isEmpty(bigTime) ||
//                TextUtils.isEmpty(FabricOrNot) ||
//                TextUtils.isEmpty(ProductLink) ||
        if (!(TextUtils.isEmpty(name) || TextUtils.isEmpty(productdetail))) {
            if (selectedPhotos.size() != 0) {
                if (!pd.isShowing())
                    pd.show();
                uploadImg();
            } else {
                uploaded = null;
                sendInquire();
            }
        } else {
            showToast("请填写名称与产品说明");
        }
    }

    public void sendInquire() {
        JSONObject json = new JSONObject();
        JSONObject json2 = new JSONObject();
        JSONArray imgList = new JSONArray();
        RequestParams params = new RequestParams();
        params.setContentType(APPLICATION_WWW);
        try {
            json2.put("token", fileHelper.getString(UserInfo.TOKEN));
            if (!(uploaded == null)) {
                json2.put("mainImage", getUploaded().get(0));
                for (int i = 0; i < getUploaded().size(); i++) {
                    imgList.put(uploaded.get(i));
                }
            }
            json.put("inquireProductName", name);
            json.put("isProductSPL", one);
            json.put("accessory", two);
            json.put("mark", three);
            json.put("pack", four);
            json.put("isChoiceMainfabric", five);
//            json.put("isChoiceMainfabric", FabricOrNot);
//            json.put("isProductSPL", DemoOrNot);
//            json.put("accessory", FabricAndAccessories);
//            json.put("mark", CommodityLabel);
//            json.put("pack", Package);
            json.put("cellPhone", fileHelper.getString(UserInfo.TEL_PHONE));
            json.put("productDetailRequire", productdetail);
//          json.put("splDeliveryTime", Time);
            json.put("predictPerOrderNumber", Time);
            json.put("predictBulkOrderTime", bigTime);
//          json.put("predictBulkOrderTime", "2013-04-22");
            json.put("storeAddress", ProductLink);
            if (two == 19) {
                json.put("status", accessoriesremarks);
            }
            json2.put("imageList", imgList);
            json2.put("inquire", json);
            json2.put("userName", fileHelper.getString(UserInfo.TEL_PHONE));
            params.addBodyParameter("data", json2.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST, Api.inquire, params,
                new RequestCallBack<String>() {

                    @Override
                    public void onFailure(HttpException arg0, String arg1) {

                        if (pd.isShowing())
                            pd.cancel();
                        showToast("提交错误");
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        JSONObject jsonObject = Tool.getJsonObject(responseInfo.result);
                        if (Tool.getString(jsonObject, "resultCode").equals("0")) {
                            showToast("提交成功");
                            if (pd.isShowing())
                                pd.cancel();
                            finish();
                        } else if (Tool.getString(jsonObject, "resultCode").equals("9002")) {
                            showToast("提交失败");
                            if (pd.isShowing())
                                pd.cancel();
                        } else if (Tool.getString(jsonObject, "resultCode").equals("9004")) {
                            showToast("提交失败");
                            if (pd.isShowing())
                                pd.cancel();
                        } else if (Tool.getString(jsonObject, "resultCode").equals("9001")) {
                            showToast("提交失败，请重新登录");
                            clearLogininfo();
                            startActivity(new Intent(context, LoginAct.class));
                            if (pd.isShowing())
                                pd.cancel();
                            finish();
                        } else if (Tool.getString(jsonObject, "resultCode").equals("9999")) {
                            showToast("数据错误");
                            if (pd.isShowing())
                                pd.cancel();
                        }
                    }

                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }

                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 0:
                    name = data.getStringExtra("name");
                    if (!"".equals(name)) {
                        strList.add(name);
                    }
                    tv_newenquiry_name.setText(name);
                    mIntent.putExtra("name", name);
                    break;
                case 1:
                    DemoOrNot = data.getStringExtra("yesorno");
                    if (!"".equals(DemoOrNot)) {
                        strList.add(DemoOrNot);
                        if (DemoOrNot.equals("是")) {
                            one = 1;
                        } else if (DemoOrNot.equals("否")) {
                            one = 0;
                        }
                        strList.add(DemoOrNot);
                    }
                    tv_newenquiry_DemoOrNot.setText(DemoOrNot);
                    mIntent.putExtra("demo", DemoOrNot);
                    break;
                case 2:
                    FabricAndAccessories = data.getStringExtra("faa");
                    if (!"".equals(FabricAndAccessories)) {
                        if (FabricAndAccessories.equals("其他")) {
                            ll_newenquiry_AccessoriesRemarks.setVisibility(View.VISIBLE);
                            findViewById(R.id.ll_AccessoriesRemarks_bar).setVisibility(View.VISIBLE);
                            two = 19;
                        } else {
                            switch (FabricAndAccessories.toString()) {
                                case "包工包料":
                                    two = 10;
                                    break;
                                case "清加工":
                                    two = 11;
                                    break;
                                case "我指定面料供应商":
                                    two = 12;
                                    break;
                            }
                            ll_newenquiry_AccessoriesRemarks.setVisibility(View.GONE);
                            findViewById(R.id.ll_AccessoriesRemarks_bar).setVisibility(View.GONE);
                        }
                        strList.add(FabricAndAccessories);
                    }
                    tv_newenquiry_FabricAndAccessories.setText(FabricAndAccessories);
                    mIntent.putExtra("faa", FabricAndAccessories);
                    break;
                case 3:
                    accessoriesremarks = data.getStringExtra("AR");
                    if (!"".equals(accessoriesremarks)) {
                        switch (accessoriesremarks.toString()) {
                            case "我提供":
                                three = 20;
                                break;
                            case "不需要":
                                three = 21;
                                break;
                            case "委托采购":
                                three = 22;
                                break;
                        }
                        strList.add(accessoriesremarks);
                    }
                    mIntent.putExtra("AR", accessoriesremarks);
                    break;
                case 4:
                    CommodityLabel = data.getStringExtra("packages");
                    if (!"".equals(CommodityLabel)) {
                        strList.add(CommodityLabel);
                    }
                    tv_newenquiry_CommodityLabel.setText(CommodityLabel);
                    mIntent.putExtra("CL", CommodityLabel);
                    break;
                case 5:
                    Package = data.getStringExtra("packages");
                    if (!"".equals(Package)) {
                        switch (Package.toString()) {
                            case "我提供":
                                four = 30;
                                break;
                            case "不需要":
                                four = 31;
                                break;
                            case "委托采购":
                                four = 32;
                                break;
                        }
                        strList.add(Package);
                    }

                    tv_newenquiry_Package.setText(Package);
                    mIntent.putExtra("packages", Package);
                    break;
                case 6:
                    Time = data.getStringExtra("numbers");
                    tv_newenquiry_Time.setText(Time);
                    mIntent.putExtra("numbers", data.getStringExtra("numbers"));
                    break;
                case 7:
                    FabricOrNot = data.getStringExtra("yesorno");
                    if (!"".equals(FabricOrNot)) {
                        strList.add(FabricOrNot);
                        if (FabricOrNot.equals("是")) {
                            five = 1;
                        } else if (FabricOrNot.equals("否")) {
                            five = 0;
                        }
                        strList.add(FabricOrNot);
                    }
                    strList.add(FabricOrNot);
                    tv_newenquiry_FabricOrNot.setText(FabricOrNot);
                    mIntent.putExtra("FON", FabricOrNot);
                    break;
                case 8:
                    ProductLink = data.getStringExtra("PL");
                    mIntent.putExtra("PL", ProductLink);
                    tvNewenquiryProductLink.setText(ProductLink);
                    break;
                case 9:
                    productdetail = data.getStringExtra("PD");
                    if (!"".equals(productdetail)) {
                        strList.add(productdetail);

                    }
                    mIntent.putExtra("PD", productdetail);
                    tvNewenquiryProductdetail.setText(productdetail);
                    break;
                case 10:
                    List<String> photos = null;
                    if (data != null) {
                        photos = data.getStringArrayListExtra(PhotoPickerActivity.KEY_SELECTED_PHOTOS);
                    }

                    selectedPhotos.clear();
                    if (photos != null) {
                        selectedPhotos.addAll(photos);
                    }
                    int count = photoAdapter.getItemCount();
                    if (count > 0) {
                        ll_newenquiry_blank.getLayoutParams().width = SCREEN_WIDTH / 4 * count;
                    }
                    photoAdapter.notifyDataSetChanged();
                    break;
                case 11:
                    bigTime = data.getStringExtra("time");
                    strList.add(bigTime);
                    if (!"".equals(bigTime)) {
                        tv_newenquiry_bigTime.setText(bigTime);
                    } else {
                        tv_newenquiry_bigTime.setText("");
                    }
                    mIntent.putExtra("bigtime", bigTime);
                    break;
            }

        }

    }

    public void uploadImg() {
        RequestParams imgParam = new RequestParams();
        final JSONObject json = new JSONObject();
        HttpUtils imgHttp = new HttpUtils();
        try {
            json.put("userName", fileHelper.getString(UserInfo.TEL_PHONE));
            json.put("token", fileHelper.getString(UserInfo.TOKEN));
            imgParam.addBodyParameter("data", json.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        for (int i = 0; i < selectedPhotos.size(); i++) {
            try {
                File f = new File(selectedPhotos.get(i));
                Bitmap bm = PictureUtil.getSmallBitmap(selectedPhotos.get(i));

                FileOutputStream fos = new FileOutputStream(new File(
                        PictureUtil.getAlbumDir(), "small_" + f.getName()));
                bm.compress(Bitmap.CompressFormat.JPEG, 40, fos);
                imgParam.addBodyParameter("fileData", new File(
                        PictureUtil.getAlbumDir(), "small_" + f.getName()));
            } catch (Exception e) {
                Logger.e(e + "");
            }
            imgHttp.send(HttpRequest.HttpMethod.POST,
                    Api.fileUpload,
                    imgParam,
                    new RequestCallBack<String>() {

                        @Override
                        public void onStart() {

                        }

                        @Override
                        public void onLoading(long total, long current, boolean isUploading) {
                        }

                        @Override
                        public void onSuccess(ResponseInfo<String> responseInfo) {
                            JSONObject jsonObject = Tool.getJsonObject(responseInfo.result);
                            Logger.json(jsonObject.toString());
                            if (Tool.getString(jsonObject, "resultCode").equals("0")) {
                                uploaded.add(Tool.getString(jsonObject, "fileId"));
                                ++imageCount;
                                if (imageCount == selectedPhotos.size()) {
                                    sendInquire();
                                }
                            } else {
                                imageCount = 0;
                                showToast("图片上传失败");
                                if (pd.isShowing())
                                    pd.cancel();
                            }
                        }

                        @Override
                        public void onFailure(HttpException arg0, String arg1) {
                            Logger.d(arg1);
                            showToast("图片上传失败");
                            if (pd.isShowing())
                                pd.cancel();
                        }
                    });
        }

    }


}
